﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using ApiBetaSeries.Model;

namespace ApiBetaSeries.Factories
{
    public class UserFactory
    {
        /// <summary>
        /// Create an user from xml
        /// </summary>
        /// <param name="user">user to update</param>
        /// <param name="xe">xml node</param>
        /// <returns>an user</returns>
        [ApiBetaSeries.Version.ApiMethod(true, "members/infos")]
        public static IUser CreateUser(IUser user, XmlNode xe)
        {
            if (user == null)
            {
                user = CreateUser();
            }

            if (!string.IsNullOrEmpty(Utils.UtilsXML.GetStringValue(xe, "login"))) { user.Login = Utils.UtilsXML.GetStringValue(xe, "login"); }
            if (!string.IsNullOrEmpty(Utils.UtilsXML.GetStringValue(xe, "url"))) { user.UrlAvatar = Utils.UtilsXML.GetStringValue(xe, "url"); }
            user.Cached = DateTime.Now;

            XmlElement xstat = xe["stats"];
            int value = -1;

            value = Utils.UtilsXML.GetIntValue(xstat, "shows");
            if (value >= 0) user.ShowNumber = value;

            value = Utils.UtilsXML.GetIntValue(xstat, "seasons");
            if (value >= 0) user.SeasonNumber = value;

            value = Utils.UtilsXML.GetIntValue(xstat, "episodes");
            if (value >= 0) user.EpisodeNumber = value;

            if (!string.IsNullOrEmpty(Utils.UtilsXML.GetStringValue(xstat, "progress"))) { user.Progress = Utils.UtilsXML.GetStringValue(xstat, "progress"); }

            value = Utils.UtilsXML.GetIntValue(xstat, "episode_to_watch");
            if (value >= 0) user.EpisodeToWatch = value;


            value = Utils.UtilsXML.GetIntValue(xstat, "time_on_tv");
            if (value >= 0) user.TimeOnTv = new TimeSpan(0, value, 0);

            value = Utils.UtilsXML.GetIntValue(xstat, "time_to_spend");
            if (value >= 0) user.TimeToSpend = new TimeSpan(0, value, 0);


            XmlElement xs = xe["shows"];
            if (xs != null)
            {
                if (user.Shows == null || xs.GetElementsByTagName("show").Count > 0)
                {
                    user.Shows = new List<IShowUser>();
                }
                foreach (XmlElement s in xs.GetElementsByTagName("show"))
                {
                    IShowUser show = ShowUserFactory.CreateShowUser(s);
                    user.Shows.Add(show);
                }
            }

            return user;
        }

        /// <summary>
        /// Create a new user
        /// </summary>
        /// <returns></returns>
        public static IUser CreateUser()
        {
            IUser user = new User();
            user.Cached = DateTime.MinValue;
            return user;
        }
    }
}
